package com.demo.resourcecode.c11mvc.deferredResult;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.async.DeferredResult;

@Controller
@RequestMapping("/async")
public class DeferredResultController {

	private static final Logger logger = LoggerFactory.getLogger(DeferredResultController.class);
	private List<DeferredResult<String>> deferredResultList = new ArrayList<>();
	// 超时时间
    private static final long OUT_OF_TIME = 30000000L;
	// 超时结果
    private static final String OUT_OF_TIME_RESULT = "out of time";

	@ResponseBody
    @GetMapping("/hello3")
    public DeferredResult<String> helloGet() throws Exception {
		logger.info("接收请求，开始处理...");

        // 建立DeferredResult对象，设置超时时间，以及超时返回超时结果
        DeferredResult<String> deferredResult = new DeferredResult<>(OUT_OF_TIME, OUT_OF_TIME_RESULT);

        deferredResult.onTimeout(() -> {
        	logger.info("调用超时");
        });

        deferredResult.onCompletion(() -> {
        	logger.info("调用完成");
        });

        // 先存起来，等待触发
        deferredResultList.add(deferredResult);

        logger.info("接收任务线程完成并退出");
        return deferredResult;
    }

    @ResponseBody
    @GetMapping("/hello4")
    public void helloSet() throws Exception {
        // 让所有hold住的请求给与响应
        deferredResultList.forEach(d -> d.setResult("say hello to all"));
    }

}
